﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookStore.Platform.objects;
using BookStore.Platform.apis;
using BookStore.Platform.spring;


namespace BookStore.Client.SiteCrawler.RanWen
{
    public class Program
    {
        private static IWebSiteApi webSiteApi = SpringContext.Current.GetObject<IWebSiteApi>();
        private static IBookListApi bookListApi = SpringContext.Current.GetObject<IBookListApi>();//("RanWenBookListApi") as RanWenBookListApi;
        private static IBookApi bookApi = SpringContext.Current.GetObject<IBookApi>();
        private static RanWenChapterApi chapterApi = SpringContext.Current.GetObject("RanWenChapterApi") as RanWenChapterApi;

        private static string index = "/index.html";
        static void Main(string[] args)
        {

            //initalize 
            //WebClient webClient = new WebClient();

            var ranwen = webSiteApi.GetByName("燃文");
            if (ranwen == null)
            {
                //create 
                webSiteApi.Save(new RanWenWebSite());
            }
            ranwen = webSiteApi.GetByName("燃文");
            //go to the ranwen site
            string bookListUrlBase = ranwen.WebSiteUrlFormat;
            string[] orders = new string[] {"A","B" };
            foreach (string bookNameOrder in orders)
            {
                //bookListApi.WebClient = webClient;
                //get max page Number
                int maxPage = bookListApi.GetMaxPageNumber(string.Format(bookListUrlBase, bookNameOrder));
                for (int i = 1; i <= maxPage; i++)
                {
                    IList<Book> inProgress = bookListApi.GetCompletedBooksFromSingleWebPage(string.Format(bookListUrlBase + "&page={1}", bookNameOrder, i), ranwen.WebSiteId);
                    // deal with these books
                    foreach (Book book in inProgress)
                    {
                        //save book
                        bookApi.Save(book);
                        //save the chapter
                        string bookCatalogUrl = book.BookCatalogUrl;
                        string baseUrl = bookCatalogUrl.Substring(0, bookCatalogUrl.IndexOf(index));
                        IDictionary<string, string> chapterUrls = chapterApi.GetChapterUrls(bookCatalogUrl, baseUrl);
                        foreach (KeyValuePair<string, string> pair in chapterUrls)
                        {
                            Chapter tmp = chapterApi.GetChapterByUrl(pair.Key, pair.Value, book.BookId);
                            chapterApi.Save(tmp);
                        }
                    }
                }
            }
            
        }
    }
}
